package com.kcl.dfss;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVlcUtil;
import org.videolan.libvlc.util.WeakHandler;

import com.kcl.dfss.view.CameraView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

public class VideoPlayerActivity extends Activity implements IVideoPlayer,
		OnClickListener {

	private RelativeLayout layout_top, layout_bottom;
	private TextView play_failname, play_time, all_time;
	private ImageView rew, play, pause, ff;
	private SeekBar seekbar;
	private Timer timer;
	private boolean state = false;

	private static String TAG = "VideoPlayerActivity";
	private CameraView mCameraView;
	private SurfaceHolder surfaceHolder = null;
	private Surface mSurface = null;
	private int mVideoWidth = 0;
	private int mVideoHeight = 0;
	private int mVideoVisibleHeight = 0;
	private int mVideoVisibleWidth = 0;
	private int mSarNum = 0;
	private int mSarDen = 0;
	private static final int UPDATE_CAMERAVIEW = 0;
	private static final String tag = "VideoPlayerActivity";
	
	
	 private static class VideoPlayerEventHandler extends WeakHandler<VideoPlayerActivity> {
	        public VideoPlayerEventHandler(VideoPlayerActivity owner) {
	            super(owner);
	        }

	        @Override
	        public void handleMessage(Message msg) {
	            VideoPlayerActivity activity = getOwner();
	            if(activity == null) return;
	            // Do not handle events if we are leaving the VideoPlayerActivity

	            switch (msg.getData().getInt("event")) {
	                case EventHandler.MediaParsedChanged:
	                    Log.i(TAG, "MediaParsedChanged");
	                    break;
	                case EventHandler.MediaPlayerPlaying:
	                    Log.i(TAG, "MediaPlayerPlaying");
	                    // Handle pause flag
//	                    if(activity.mPauseOnLoaded) {
//	                        activity.mPauseOnLoaded = false;
//	                        activity.mLibVLC.pause();
//	                        activity.setOverlayProgress();
//	                    }
//	                    activity.stopLoadingAnimation();
//	                    activity.showOverlay();
//	                    /** FIXME: update the track list when it changes during the
//	                     *  playback. (#7540) */
//	                    activity.setESTrackLists(true);
//	                    activity.setESTracks();
//	                    activity.changeAudioFocus(true);
//	                    activity.updateNavStatus();
	                    break;
	                case EventHandler.MediaPlayerPaused:
	                    Log.i(TAG, "MediaPlayerPaused");
	                    break;
	                case EventHandler.MediaPlayerStopped:
	                    Log.i(TAG, "MediaPlayerStopped");
//	                    activity.changeAudioFocus(false);
	                    break;
	                case EventHandler.MediaPlayerEndReached:
	                    Log.i(TAG, "MediaPlayerEndReached");
//	                    activity.changeAudioFocus(false);
//	                    activity.endReached();
	                    break;
	                case EventHandler.MediaPlayerVout:
//	                    activity.updateNavStatus();
//	                    if (!activity.mHasMenu)
//	                        activity.handleVout(msg);
	                    break;
	                case EventHandler.MediaPlayerPositionChanged:
//	                    if (!activity.mCanSeek)
//	                        activity.mCanSeek = true;
	                    //don't spam the logs
	                    break;
	                case EventHandler.MediaPlayerEncounteredError:
	                    Log.i(TAG, "MediaPlayerEncounteredError");
//	                    activity.encounteredError();
	                    break;
	                case EventHandler.HardwareAccelerationError:
	                    Log.i(TAG, "HardwareAccelerationError");
//	                    activity.handleHardwareAccelerationError();
	                    break;
	                case EventHandler.MediaPlayerTimeChanged:
	                    // avoid useless error logs
	                    break;
	                default:
	                    Log.e(TAG, String.format("Event not handled (0x%x)", msg.getData().getInt("event")));
	                    break;
	            }
//	            activity.updateOverlayPausePlay();
	        }
	    };
	 /**
     *  Handle libvlc asynchronous events
     */
    private final Handler eventHandler = new VideoPlayerEventHandler(this);

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.d(TAG, "mVideoWidth is " + mVideoWidth + " mVideoheight is "
					+ mVideoHeight);
			int code = msg.what;
			switch (code) {
			case UPDATE_CAMERAVIEW:
				mCameraView.setSurfaceSize(mVideoWidth, mVideoHeight);
				break;
			}
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_videoplayer);
		mCameraView = (CameraView) findViewById(R.id.cameraview);
		mCameraView.setVedioPlayerCallback(this);
		String url = "rtsp://192.168.1.1:8654/media/"
				+ getIntent().getStringExtra("URL") + ".mkv";
		// String url ="rtsp://192.168.1.1:8654/media/20150501_202020.mkv";
		mCameraView.setRTSPPathAndPlay(url);

		// 每隔0.5s执行一次判断视频是否开始播放
		timer = new Timer();
		timer.schedule(new MyTask(), 50, 500);

		// just test
		layout_top = (RelativeLayout) findViewById(R.id.layout_top);
		layout_bottom = (RelativeLayout) findViewById(R.id.layout_bottom);
		play_failname = (TextView) findViewById(R.id.play_filename);
		play_time = (TextView) findViewById(R.id.play_time);
		all_time = (TextView) findViewById(R.id.all_time);
		rew = (ImageView) findViewById(R.id.rew);
		play = (ImageView) findViewById(R.id.start);
		pause = (ImageView) findViewById(R.id.pause);
		ff = (ImageView) findViewById(R.id.ff);
		seekbar = (SeekBar) findViewById(R.id.seekBar1);

		play_failname.setText(getIntent().getStringExtra("URL"));
		play.setEnabled(false);
		play.setVisibility(View.GONE);

		layout_top.setOnClickListener(this);
		layout_bottom.setOnClickListener(this);
		mCameraView.setOnClickListener(this);
		rew.setOnClickListener(this);
		play.setOnClickListener(this);
		pause.setOnClickListener(this);
		ff.setOnClickListener(this);

		EventHandler em = org.videolan.libvlc.EventHandler.getInstance();
		em.addHandler(eventHandler);
		

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cameraview:
			if (state) {
				layout_top.setVisibility(View.VISIBLE);
				layout_bottom.setVisibility(View.VISIBLE);
				state = false;
			} else {
				layout_top.setVisibility(View.GONE);
				layout_bottom.setVisibility(View.GONE);
				state = true;
			}
			break;
		case R.id.rew:
			if (mCameraView.getPlayState()) {
				int currentPosition = mCameraView.getPosition();
				if (currentPosition - 5000 > 0) {
					mCameraView.setPosition(currentPosition - 5000);
				}
			}
			break;
		case R.id.start:
			mCameraView.resume();
			play.setEnabled(false);
			play.setVisibility(View.GONE);
			pause.setEnabled(true);
			pause.setVisibility(View.VISIBLE);
			break;
		case R.id.pause:
			mCameraView.pause();
			pause.setEnabled(false);
			pause.setVisibility(View.GONE);
			play.setEnabled(true);
			play.setVisibility(View.VISIBLE);
			break;
		case R.id.ff:
			if (mCameraView.getPlayState()) {
				int currentPlsition = mCameraView.getPosition();
				if (currentPlsition + 5000 < mCameraView.getLength()) {
					mCameraView.setPosition(currentPlsition + 5000);
				}
			}
			break;
		case R.id.layout_top:

			break;
		case R.id.layout_bottom:

			break;
		default:

			break;
		}
	}

	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
		mCameraView.pause();
	}

	@SuppressLint("NewApi")
	public void onResume() {
		super.onResume();
		mCameraView.resume();
	}

	public void onDestroy() {
		super.onDestroy();
		EventHandler em = EventHandler.getInstance();
        em.removeHandler(eventHandler);
		mCameraView.destroy();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		mCameraView.destroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { // 竖屏
			mCameraView.setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, 500));
		} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { // 横屏
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			mCameraView.setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		}

	}

	@Override
	public void setSurfaceLayout(int width, int height, int visible_width,
			int visible_height, int sar_num, int sar_den) {
		// TODO Auto-generated method stub
		mVideoHeight = height;
		mVideoWidth = width;
		mVideoVisibleHeight = visible_height;
		mVideoVisibleWidth = visible_width;
		mSarNum = sar_num;
		mSarDen = sar_den;
		// Message msg = mHandler.obtainMessage(SURFACE_LAYOUT);
		// mHandler.sendMessage(msg);
		mHandler.sendEmptyMessage(UPDATE_CAMERAVIEW);
	}

	@Override
	public int configureSurface(Surface surface, final int width,
			final int height, final int hal) {
		// TODO Auto-generated method stub
		if (LibVlcUtil.isICSOrLater() || surface == null)
			return -1;
		if (width * height == 0)
			return 0;
		Log.d(TAG, "configureSurface: " + width + "x" + height);

		final ConfigureSurfaceHolder holder = new ConfigureSurfaceHolder(
				surface);

		final Handler handler = new Handler(Looper.getMainLooper());
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (mSurface == holder.surface && surfaceHolder != null) {
					if (hal != 0)
						surfaceHolder.setFormat(hal);
					surfaceHolder.setFixedSize(width, height);
				}

				synchronized (holder) {
					holder.configured = true;
					holder.notifyAll();
				}
			}
		});

		try {
			synchronized (holder) {
				while (!holder.configured)
					holder.wait();
			}
		} catch (InterruptedException e) {
			return 0;
		}
		return 1;
	}

	@Override
	public void eventHardwareAccelerationError() {
		// TODO Auto-generated method stub

	}

	private static class ConfigureSurfaceHolder {
		private final Surface surface;
		private boolean configured;

		private ConfigureSurfaceHolder(Surface surface) {
			this.surface = surface;
		}
	}

	public class MyTask extends TimerTask {
		public void run() {
			/*
			 * Message message=new Message(); message.what=1;
			 * updateHandler.sendMessage(message);
			 */
			Log.i(TAG, "是否正在播放：" + mCameraView.getPlayState());
			if (mCameraView.getPlayState()) {
				Message message = new Message();
				message.what = 1;
				updateHandler.sendMessage(message);
			}
		}
	}

	// 更新进度条和时间显示
	private final Handler updateHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Time currentTime = new Time(mCameraView.getPosition());
				Time allTime = new Time(mCameraView.getLength());
				String timestr = currentTime.toString();
				String timestr2 = allTime.toString();

				Log.i(TAG,
						"当前时间：" + timestr.substring(timestr.indexOf(":") + 1));
				Log.i(TAG,
						"总时间：" + timestr2.substring(timestr2.indexOf(":") + 1));

				play_time.setText(timestr.substring(timestr.indexOf(":") + 1));
				all_time.setText(timestr2.substring(timestr2.indexOf(":") + 1));
				int progressValue = 0;
				if (mCameraView.getLength() > 0) {
					progressValue = (int) (seekbar.getMax()
							* mCameraView.getPosition() / mCameraView
							.getLength());
				}
				seekbar.setProgress(progressValue);
				break;
			}
			super.handleMessage(msg);
		}
	};
	// @Override
	// public void setSurfaceLayout(int arg0, int arg1, int arg2, int arg3,
	// int arg4, int arg5) {
	// // TODO Auto-generated method stub
	// mVideoWidth = arg0;
	// mVideoHeight = arg1;
	// mHandler.sendEmptyMessage(UPDATE_CAMERAVIEW);
	// }

}
